# inspection/serializers.py
from rest_framework import serializers
from .models import Image, Video, DetectionResult
import logging
import requests

logger = logging.getLogger(__name__)

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ['id', 'image', 'uploaded_at']

class VideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Video
        fields = ['id', 'video', 'detected_video', 'uploaded_at']
        read_only_fields = ['detected_video', 'uploaded_at']

    def validate_video(self, value):
        if not value:
            raise serializers.ValidationError("请提供视频文件")
        # 验证文件大小（500MB）
        if value.size > 500 * 1024 * 1024:
            raise serializers.ValidationError("视频文件大小不能超过500MB")
        # 验证文件类型
        content_type = value.content_type
        allowed_types = ['video/mp4', 'video/avi', 'video/mpeg', 'video/quicktime']
        if content_type not in allowed_types:
            raise serializers.ValidationError("不支持的视频格式")
        return value

    def create(self, validated_data):
        try:
            instance = super().create(validated_data)
            return instance
        except Exception as e:
            logger.error(f"创建视频实例时出错: {str(e)}")
            raise serializers.ValidationError(str(e))

    def get_video_url(self, obj):
        try:
            if obj.video:
                url = obj.video.url
                logger.debug(f"获取视频URL成功: {url}")
                return url
            logger.warning(f"视频对象 {obj.id} 没有视频文件")
            return None
        except Exception as e:
            logger.error(f"获取视频URL失败: {str(e)}", exc_info=True)
            return None

    def get_detected_video_url(self, obj):
        try:
            if obj.detected_video:
                url = obj.detected_video.url
                logger.debug(f"获取检测后视频URL成功: {url}")
                return url
            logger.warning(f"视频对象 {obj.id} 没有检测后的视频文件")
            return None
        except Exception as e:
            logger.error(f"获取检测后视频URL失败: {str(e)}", exc_info=True)
            return None

# Add to serializers.py
from rest_framework import serializers
from .models import DetectionResult

class DetectionResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = DetectionResult
        fields = ['id', 'video', 'class_id', 'class_name', 'start_time', 'end_time', 'confidence', 'count', 'created_at']
        read_only_fields = ['id', 'created_at']